package com.dede.net_speed_monitor.fragment;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

import com.dede.net_speed_monitor.R;
import com.dede.net_speed_monitor.service.NetMonitorService;
import com.dede.net_speed_monitor.service.NetTileService;
import com.dede.net_speed_monitor.util.ServiceUtil;

/**
 * Created by Hsh
 * in 2017/5/20 020 5:22 下午 on ACER-PC computer.
 * doc.
 */
public class SettingFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

    private LocalBroadcastManager mLocalBroadcastManager;
    private NetTileService.SettingChangeBroadcastReceiver mSettingsChangeBroadcastReceiver;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.setting_list);
        PreferenceManager.setDefaultValues(getActivity(), R.xml.setting_list, false);

        SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
        sp.registerOnSharedPreferenceChangeListener(this);
        boolean serviceRunning = ServiceUtil.isServiceRunning(getActivity(), NetMonitorService.class.getName());
        sp.edit().putBoolean(getString(R.string.notify_service_state_key), serviceRunning).apply();
//        Preference preference = findPreference(getString(R.string.notify_service_state_key));
//        preference.setSummary(serviceRunning ? "已开启" : "已关闭");

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {//低于7.0，隐藏磁贴设置
            findPreference(getString(R.string.notify_auto_remove_key)).setEnabled(false);
            findPreference("tile_group").setEnabled(false);
        }
        findPreference(getString(R.string.notify_auto_remove_key))
                .setSummary(getString(R.string.notify_auto_remove_text,
                        sp.getBoolean(getString(R.string.notify_auto_remove_key), true) ? "自动" : "不"));

        mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter filter = new IntentFilter(NetTileService.SettingChangeBroadcastReceiver.ACTION_SETTING_CHANGE);
        mSettingsChangeBroadcastReceiver = new NetTileService.SettingChangeBroadcastReceiver();
        mLocalBroadcastManager.registerReceiver(mSettingsChangeBroadcastReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
        if (mSettingsChangeBroadcastReceiver != null) {
            mLocalBroadcastManager.unregisterReceiver(mSettingsChangeBroadcastReceiver);
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
        if (key == null)
            return;
        if (key.equals(getString(R.string.notify_service_state_key))) {//服务状态
            boolean serviceState = sp.getBoolean(key, false);
            boolean isRunning = ServiceUtil.isServiceRunning(getActivity(), NetMonitorService.class.getName());
            if (serviceState && !isRunning) {
                Intent intent = new Intent(getActivity(), NetMonitorService.class);
                getActivity().startService(intent);
                findPreference(key).setSummary("已开启");
            } else if (!serviceState && isRunning) {
                Intent intent = new Intent(getActivity(), NetMonitorService.class);
                getActivity().stopService(intent);
                findPreference(key).setSummary("已关闭");
            }
        } else if (key.equals(getString(R.string.notify_auto_remove_key))) {//自动移除通知
            findPreference(key).setSummary(getString(R.string.notify_auto_remove_text,
                    sp.getBoolean(key, true) ? "自动" : "不"));
        } else if (key.equals(getString(R.string.notify_update_interval_key))) {//通知更新频率
            findPreference(key).setSummary(getString(R.string.notify_update_interval_key) + "ms");
        } else if (key.equals(getString(R.string.notify_show_mode_key))) {//显示模式
            int index = Integer.valueOf(sp.getString(key, "0"));
            String[] modes = getResources().getStringArray(R.array.notify_net_modes);
            findPreference(key).setSummary(modes[index]);

        } else if (key.equals(getString(R.string.tile_text_style_key))) {//字体样式
            String[] styles = getResources().getStringArray(R.array.tile_text_style);
            int value = Integer.valueOf(sp.getString(key, "0"));
            findPreference(key).setSummary(styles[value]);
            mLocalBroadcastManager.sendBroadcast(
                    new Intent(NetTileService.SettingChangeBroadcastReceiver.ACTION_SETTING_CHANGE));
        } else if (key.equals(getString(R.string.tile_text_color_key))) {//字体颜色
            String color = sp.getString(key, "FFCCCCCC");
            try {
                int parseColor = Color.parseColor("#" + color);
                findPreference(key).setSummary("#" + color);
                mLocalBroadcastManager.sendBroadcast(
                        new Intent(NetTileService.SettingChangeBroadcastReceiver.ACTION_SETTING_CHANGE));
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                sp.edit().putString(key, "FFCCCCCC").apply();
                Toast.makeText(getActivity(), "颜色代码错误", Toast.LENGTH_SHORT).show();
            }
            if (color.length() == 8 && color.startsWith("00")) {
                Toast.makeText(getActivity(), "全透明颜色，字体可能无法显示", Toast.LENGTH_SHORT).show();
            }
        } else if (key.equals(getString(R.string.tile_update_interval_key))) {//更新频率
            findPreference(key).setSummary(getString(R.string.tile_update_interval_key) + "ms");
            mLocalBroadcastManager.sendBroadcast(
                    new Intent(NetTileService.SettingChangeBroadcastReceiver.ACTION_SETTING_CHANGE));
        } else if (key.equals(getString(R.string.tile_text_size_key))) {//字体大小
            String value = sp.getString(key, "12");
            findPreference(key).setSummary(value + "sp");
            mLocalBroadcastManager.sendBroadcast(
                    new Intent(NetTileService.SettingChangeBroadcastReceiver.ACTION_SETTING_CHANGE));
        }
    }
}
